%
% Author: Vasyl Mykhalchuk
%
%
function [scalarFields] = nextSF( obj_target, obj_ref, adjList, adjVertList )
%{
[vertices, faces] = read_wobj(fileName);
obj_target.vertices = vertices;
obj_target.faces = faces;
%}

numberOfFaces = obj_ref.nF;
numberOfVertices = obj_ref.nV;

% time-varying scalar field (vertex based)
scalarFields = zeros(numberOfVertices, 1, 'double');
% time-varying scalar field (triangle based)
scalarFieldsT = zeros(numberOfFaces, 1, 'double');

faces = obj_ref.faces;

% =============== ============== ===========
% LOG('Computing faces scalar field');
for iFace = 1:numberOfFaces
    tr = faces(iFace,:);
    v1 = obj_ref.vertices(tr(1), 1:3);
    v2 = obj_ref.vertices(tr(2), 1:3);
    v3 = obj_ref.vertices(tr(3), 1:3);
    
    vv1 = obj_target.vertices(tr(1), 1:3);
    vv2 = obj_target.vertices(tr(2), 1:3);
    vv3 = obj_target.vertices(tr(3), 1:3);
    
    %flatten triangles 
    %[v1f, v2f, v3f] = fitTrianglesToOnePlane(v1, v2, v3);
    %[vv1f, vv2f, vv3f] = fitTrianglesToOnePlane(vv1, vv2, vv3);
    
    %strains = tri2D_strain(v1f, v2f, v3f, vv1f, vv2f, vv3f);
    %strains = strainPortCPP(v1f, v2f, v3f, vv1f, vv2f, vv3f);
    strains = strainPortCPP(v1, v2, v3, vv1, vv2, vv3);
    kTreshold = 0.02;
    if( abs(strains(1)) > kTreshold )
        scalarFieldsT(iFace) = strains(1);
    else 
        scalarFieldsT(iFace) = 0.0;
    end%if
end%for


% compute vertex-based time-varying scalar field
LOG('Computing vertex scalar field');
deformationMax = 0.0;
deformationMin = 0.0;
for iVertex = 1:numberOfVertices
        i = 1;
        scalarValue = 0.0;
        adjTriangle = adjList(iVertex,i);
        while (adjTriangle ~= 0)
            tr = faces(adjTriangle,:);
            
            v1 = obj_target.vertices(tr(1), 1:3);
            v2 = obj_target.vertices(tr(2), 1:3);
            v3 = obj_target.vertices(tr(3), 1:3);
            
            % trArea = triangleArea(v1,v2,v3)*10;
            trArea = 1;
            scalarValue = scalarValue + trArea * scalarFieldsT(adjTriangle);
            i = i + 1;
            adjTriangle = adjList(iVertex,i);
        end
        if scalarValue > deformationMax
            deformationMax = scalarValue;
        end%if
        if scalarValue < deformationMin
            deformationMin = scalarValue;
        end%if
        scalarFields(iVertex) = scalarValue;
end%for

end%function nextSF

